#include <iostream>
#include <string>
using namespace std;

class Solution {
public:
    int longestValidParentheses(string s)
    {
        int left = 0, right = 0;
        int left_max = 0;

        for (size_t i = 0; i <= s.size(); i++)
        {
            if (s[i] == '(')    left++;
            else if (s[i] == ')')    right++;

            if (left == right)   left_max = left_max < 2 * left ? 2 * left : left_max;

            if (right > left)
            {
                left_max = left_max < right + left - 1 ? right + left - 1 : left_max;
                left = right = 0;
            }
        }

        left = right = 0;
        int right_max = 0;
        for (int i = s.size() - 1; i >= 0; i--)
        {
            if (s[i] == '(')     left++;
            else if (s[i] = ')') right++;

            if (left == right)   right_max = right_max < 2 * left ? 2 * left : right_max;

            if (left > right)
            {
                right_max = right_max < left + right - 1 ? right + left - 1 : right_max;
                left = right = 0;
            }
        }

        return right_max < left_max ? left_max : right_max;
    }
};

int main()
{
    Solution().longestValidParentheses("(()");
    return 0;
}